package group.hhsw.purchase.controller;

import group.hhsw.common.model.vo.DetailOrder;
import group.hhsw.common.model.params.Check;
import group.hhsw.purchase.utils.CombineBeans;
import group.hhsw.common.utils.Result;
import group.hhsw.purchase.service.impl.PurchaseContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/purchase")
public class PurchaseController {

    @Autowired
    private PurchaseContext purchaseContext;

    @PostMapping
    public Result purchase(@RequestBody Check check) {
        List<DetailOrder> detailOrders = new ArrayList<>();
        String proServices = purchaseContext.getProService(check.getProductId());
        if (!(purchaseContext.getAtomicService("1").atomicService(check).getLoginIsOk())) {
            return Result.fail(6004,"请登录后购买");
        }
        DetailOrder res = new DetailOrder();
        res.setLoginIsOk(true);
        if (proServices != null) {
            String s = proServices.trim();
            String[] services = s.split(",");
            for (String num: services) {
                DetailOrder detailOrder = purchaseContext.getAtomicService(num).atomicService(check);
                detailOrders.add(detailOrder);
            }
            //汇总所有接口的结果
            for(DetailOrder d : detailOrders) {
                CombineBeans.copyNotNull(d, res);
            }
        }
        BeanUtils.copyProperties(check,res);
        return Result.success(res);
    }
}
